require(['jquery','knockout','bootstrap', 'uui', 'tree', 'grid', 'ip'], function ($, ko) {
	window.ko = ko;
	var currentPage = 1;
	var totalCount;
	var limit;
	var flag = 0;
	var viewModel = {
		//ruleName: ko.observable(viewModel.gridDataTable.meta.rule_name),
		//定值规则树数据模型
		listDataTable: new u.DataTable({
			meta : {
				'cid' : {
					type : 'string'
				},
				'pid' : {
					type : 'string'
				},
				'cname' : {
					type : 'string'
				}
			}
		}),
		treeSetting: {
			view: {
				showLine: false,
				selectedMulti: true,
			},
			callback: {
				onClick: function (e, id, node) {
					
				}
			}
		},
		//表格数据模型
		gridDataTable: new u.DataTable({
			meta: {
//				'column': {type: 'string'},
				'bname': {type: 'string'},
				'press': {type: 'string'},
				'author': {type: 'string'}
			}
		})
	};
	
	function showgrid() {
		$.ajax({
			type : "GET",
			url : "/bookstore/my/findAll",
			data : {
				"currentPage" : currentPage,
				"limit" : 10
			}, 
			dataType : 'json',
			success : function(result) {
				viewModel.gridDataTable.clear();
				var data = result.data;
				viewModel.gridDataTable.setSimpleData(data);
				//设置分页插件所需参数
				totalCount = result.totalCount;
		    	limit = 10;
		    	if (!flag) { // 保证分页插件只生成一次
		    		flag = 1;
		    		callBackPagination(totalCount, limit);
		    	}
			},
			error : function() {
				alert("网络有问题吧。。。");
			}
		})
	};
	
	//请求数据，刷新左侧定值规则树
    function getTree(){
        $.ajax({
            type: 'GET',
            url: "/bookstore/my/findTree",
            dataType: 'json',
            success: function (result) {
            	viewModel.listDataTable.setData(result.data);
            	console.log(result);
            	//展开所有子节点
        		var treeObj = $.fn.zTree.getZTreeObj("tree2");
        		console.log(treeObj);
        		treeObj.expandAll(true);
            },
            error: function () {
            	alert("树不出来，网络有问题吧。。。");
            }
        });
    };
    
    /**
     * 分页插件
     * callback:点击事件
     */
    function callBackPagination(totalCount, limit) {
        $('#callBackPager').extendPagination({
            totalCount: totalCount, //总页数
            showCount: 10,          //展示选项数
            limit: limit,           //每页条数
            callback: function (cur, limit, totalCount) {
            	currentPage = cur;
            	showgrid();
            	//alert('当前页：' + cur + '每页条数：' + limit + '总数：' + totalCount);
            }
        });
    }

	function init(){
		showgrid();
		getTree();
		//ko.cleanNode($("#list-page")[0]);
		var app = u.createApp(
				{
					el: '#first',
					model: viewModel
				}
		);
    };
    

    init();

});